import { ProCard, StatisticCard } from '@ant-design/pro-components';
import { Input, Select, Spin } from 'antd';
import { useEffect, useState } from 'react';
import { getWeather, searchAddress, getLocation } from '../../api/gd';

export default () => {
  const [map, setMap] = useState(null);
  const [weather, setWeather] = useState(null);
  const [location, setLocation] = useState(null);
  const [keyword, setKeyword] = useState('');
  const [options, setOptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchCity, setSearchCity] = useState('');
  const [debugInfo, setDebugInfo] = useState({
    weather: null,
    location: null,
    lastUpdated: null,
  });
  const [showOptions, setShowOptions] = useState(true); // 新增状态控制选择框显示
  const [userLocation, setUserLocation] = useState(null); // 存储用户地理位置

  // 获取用户当前位置
  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          setUserLocation({ latitude, longitude });
          // 根据经纬度获取城市信息
          reverseGeocode(latitude, longitude);
        },
        (error) => {
          console.error('获取位置失败:', error);
          // 如果无法获取当前位置，使用默认城市
          setSearchCity('合肥');
          fetchWeather('合肥');
          fetchLocation('合肥');
        }
      );
    } else {
      console.error('浏览器不支持地理定位');
      setSearchCity('合肥');
      fetchWeather('合肥');
      fetchLocation('合肥');
    }
  }, []);

  // 逆地理编码获取地址信息
  const reverseGeocode = async (latitude, longitude) => {
    try {
      const res = await getLocation(`POINT(${longitude} ${latitude})`);
      if (res.status === '1' && res.info === 'OK' && res.geocodes?.length > 0) {
        const geoData = res.geocodes[0];
        const city = geoData.city || geoData.district || geoData.province;
        setSearchCity(city);
        setKeyword(city);
        fetchWeather(city);
        fetchLocation(city);
      } else {
        throw new Error(res.info || '位置数据获取失败');
      }
    } catch (err) {
      console.error('逆地理编码失败:', err);
      setSearchCity('合肥');
      setKeyword('合肥');
      fetchWeather('合肥');
      fetchLocation('合肥');
    }
  };

  // 初始化地图
  useEffect(() => {
    if (window.AMap) {
      const initMap = new window.AMap.Map('map-container', {
        zoom: 12,
        center: [116.397428, 39.90923]
      });
      setMap(initMap);

      return () => {
        if (initMap) {
          initMap.destroy();
        }
      };
    }
  }, []);

  // 获取默认城市的天气和位置信息
  // 已在useEffect中处理，默认使用当前位置或回退到合肥

  // 修改天气数据获取函数
  const fetchWeather = (city) => {
    if (!city) return;
    
    getWeather(city)
      .then(res => {
        if (res.status === '1' && res.info === 'OK' && res.forecasts?.length > 0) {
          const forecast = res.forecasts[0];
          // console.log('天气数据:', forecast);
          // 提取今日天气信息
          const todayForecast = forecast.casts?.[0] || {};
          
          const weatherData = {
            city: forecast.city,
            province: forecast.province,
            reportTime: forecast.reporttime,
            dayWeather: todayForecast.dayweather,
            nightWeather: todayForecast.nightweather,
            dayTemp: todayForecast.daytemp,
            nightTemp: todayForecast.nighttemp,
            dayWind: todayForecast.daywind,
            dayPower: todayForecast.daypower,
            humidity: '-', // 天气接口未提供湿度信息
          };
          
          setWeather(weatherData);
          
          setDebugInfo(prev => ({
            ...prev,
            weather: res,
            lastUpdated: new Date().toLocaleTimeString()
          }));
          
          console.log('天气接口响应:', res);
        } else {
          throw new Error(res.info || '天气数据获取失败');
        }
      })
      .catch(err => {
        console.error('天气接口错误:', err);
        setDebugInfo(prev => ({ ...prev, weather: { error: err.message } }));
      });
  };

  // 修改位置数据获取函数
  const fetchLocation = (city) => {
    if (!city) return;
    
    getLocation(city)
      .then(res => {
        if (res.status === '1' && res.info === 'OK' && res.geocodes?.length > 0) {
          const geoData = res.geocodes[0];
          setLocation(geoData);
          
          setDebugInfo(prev => ({
            ...prev,
            location: res,
            lastUpdated: new Date().toLocaleTimeString()
          }));
          
          // console.log('位置接口响应:', res);
        } else {
          throw new Error(res.info || '位置数据获取失败');
        }
      })
      .catch(err => {
        console.error('位置接口错误:', err);
        setDebugInfo(prev => ({ ...prev, location: { error: err.message } }));
      });
  };

  // 搜索地址并更新天气和位置信息
  const handleSearch = (value) => {
    if (!value) {
      // 如果搜索框为空，使用当前位置或默认城市
      if (userLocation) {
        reverseGeocode(userLocation.latitude, userLocation.longitude);
      } else {
        setSearchCity('合肥');
        setKeyword('合肥');
        fetchWeather('合肥');
        fetchLocation('合肥');
      }
      return;
    }

    setLoading(true);

    searchAddress({
      keywords: value,
      city: value // 使用输入值作为搜索城市
    })
      .then(res => {
        if (res.status === '1' && res.geocodes?.length) {
          const suggestions = res.geocodes.map((geo, index) => ({
            value: geo.formatted_address,
            label: geo.formatted_address,
            key: index
          }));
          setOptions(suggestions);
          setShowOptions(suggestions.length > 0);
          
          // 如果找到结果，自动选择第一个结果并更新地图、天气和位置
          if (suggestions.length > 0) {
            const selected = suggestions[0];
            const [lng, lat] = selected.location.split(',');
            map?.setCenter([parseFloat(lng), parseFloat(lat)]);
            map?.setZoom(14); // 调整缩放级别

            const city = selected.city || selected.district || selected.province;
            setSearchCity(city);
            setKeyword(value);
            fetchWeather(city);
            fetchLocation(city);
          }
        } else {
          setOptions([]);
          setShowOptions(false);
          // 如果没有找到精确匹配，尝试直接使用输入值
          if (value) {
            setSearchCity(value);
            setKeyword(value);
            fetchWeather(value);
            fetchLocation(value);
            
            // 获取该城市的地理编码以调整地图显示
            getLocation(value).then(geoRes => {
              if (geoRes.status === '1' && geoRes.geocodes?.length) {
                const geoData = geoRes.geocodes[0];
                const [lng, lat] = geoData.location.split(',');
                map?.setCenter([parseFloat(lng), parseFloat(lat)]);
                map?.setZoom(12);
              }
            });
          }
        }
      })
      .catch(err => {
        console.error('搜索地址错误:', err);
        setOptions([]);
        setShowOptions(false);
      })
      .finally(() => {
        setLoading(false);
      });
  };
 
  // 当选择地址时更新地图、天气和位置信息
  const handleChange = (value) => {
    const selected = options.find(opt => opt.value === value);
    if (selected) {
      const [lng, lat] = selected.location.split(',');
      map?.setCenter([parseFloat(lng), parseFloat(lat)]);

      const city = selected.city || selected.district || selected.province;
      setSearchCity(city);
      setKeyword(value);
      fetchWeather(city);
      fetchLocation(city);
    }
  };

  return (
    <>
      <ProCard
        title="地图展示"
        bordered
        headerBordered
        gutter={16}
        extra={
          <Select
            show-search
            onSearch={handleSearch}
            onChange={handleChange} // 用于处理下拉选项选择
            loading={loading}
            options={options}
            style={{ width: 400 }}
            placeholder="输入地址搜索"
            filter-option={() => true}
            mode="tags"
            open={showOptions}
            onBlur={() => setShowOptions(false)}
            onFocus={() => options.length > 0 && setShowOptions(true)}
            value={keyword} // 绑定输入框的值
          />
        }
      >
        <div id="map-container" style={{ width: '100%', height: '400px' }} />
      </ProCard>

      <ProCard
        title="信息面板"
        bordered
        headerBordered
        gutter={16}
        style={{ marginTop: 16 }}
      >
        <ProCard title={`天气信息 - ${searchCity}`} type="inner" bordered>
          {weather ? (
            <>
              <div>城市：{weather.city}</div>
              <div>省份：{weather.province}</div>
              <div>报告时间：{weather.reportTime}</div>
              <div>白天天气：{weather.dayWeather}（{weather.dayTemp}℃）</div>
              <div>夜间天气：{weather.nightWeather}（{weather.nightTemp}℃）</div>
              <div>风向/风力：{weather.dayWind}/{weather.dayPower}</div>
            </>
          ) : (
            <Spin size="small" />
          )}</ProCard>
        <ProCard title={`位置信息 - ${searchCity}`} type="inner" bordered>
          {location ? (
            <> 
              <div>地址：{location.formatted_address}</div>
              <div>坐标：{location.location}</div>
            </>
          ) : (
            <Spin size="small" />
          )}</ProCard>
      </ProCard>

      <ProCard
        title="调试信息"
        bordered
        headerBordered
        gutter={16}
        style={{ marginTop: 16 }}
      >
        <StatisticCard
          title="天气接口信息"
          statistic={{
            value: debugInfo.weather ? '已加载' : '未加载',
            prefix: debugInfo.weather ? '✅' : '❌',
          }}
          footer={`最后更新时间: ${debugInfo.lastUpdated || 'N/A'}`}
          style={{ width: '100%' }}
        />
        <StatisticCard
          title="位置接口信息"
          statistic={{
            value: debugInfo.location ? '已加载' : '未加载',
            prefix: debugInfo.location ? '✅' : '❌',
          }}
          footer={`最后更新时间: ${debugInfo.lastUpdated || 'N/A'}`}
          style={{ width: '100%', marginTop: 16 }}
        />
      </ProCard>
    </>
  );
};